//
//  HOUIMgr.m
//  WeiDu_1_0
//
//  Created by foguo-mac-1 on 01/07/16.
//  Copyright (c) 2016 WeiDu Energy Tech. All rights reserved.
//

#import "HOUIMgr.h"
#import "Logger.h"
#import "HOHttpMgr.h"
#import "HOConstants.h"
#import "HOStaticDataMgr.h"

#import "HOMessageController.h"
#import "HOUserInfoController.h"
#import "HOAppController.h"
#import "HOTabViewController.h"
#import "HOAppController.h"
#import "HOAppDataModule.h"
#import "HOMyController.h"
#import "HOLoginViewController.h"
#import "HOMessageController.h"
#import "HODefine.h"
#import "HOUserInfoDataModule.h"
#import "HOWelcomeController.h"
#import "HOQuickReportViewController.h"
#import "HOMyViewController.h"
#import "HOMessageViewController.h"
#import "Logger.h"
#import "HOGlobalData.h"
// 如果需要使用idfa功能所需要引入的头文件（可选）
#import <AdSupport/AdSupport.h>
#import "HOJPushHandler.h"
// 引入JPush功能所需头文件
#import "JPUSHService.h"
// iOS10注册APNs所需头文件

static HOUIMgr *_instace;
@implementation HOUIMgr
+ (HOUIMgr *)sharedInstance
{
    if(_instace == nil)
    {
        _instace = [[HOUIMgr alloc]init];
    }
    return _instace;
}
- (instancetype)init
{
    if(self = [super init])
    {
        controlerListenerDic = [[NSMutableDictionary alloc] init];
		userInfoDic = [[NSMutableDictionary alloc] init];
        httpMgr = [[HOHttpMgr alloc] init];
        httpMgr.delegate = self;
		[HOStaticDataMgr sharedInstance];
		
		[HOGlobalData sharedInstance].caiYunUser = [[[HOCaiyunUser alloc] init] autorelease];
        
		NSObject<HOControllerDelegate> *controller = nil;
		
		controller = [[HOAppController alloc] initWithModuleType:HO_MODULE_TYPE_APP];
        [controlerListenerDic setObject:controller forKey:[NSNumber numberWithInt:HO_MODULE_TYPE_APP]];
        [controller release];
        
        controller = [[HOUserInfoController alloc] initWithModuleType:HO_MODULE_TYPE_USER];
        [controlerListenerDic setObject:controller forKey:[NSNumber numberWithInt:HO_MODULE_TYPE_USER]];
        [controller release];
        
        controller = [[HOMessageController alloc] initWithModuleType:HO_MODULE_TYPE_MESSAGE];
        [controlerListenerDic setObject:controller forKey:[NSNumber numberWithInt:HO_MODULE_TYPE_MESSAGE]];
        [controller release];
		
        controller = [[HOMyController alloc] initWithModuleType:HO_MODULE_TYPE_MY];
        [controlerListenerDic setObject:controller forKey:[NSNumber numberWithInt:HO_MODULE_TYPE_MY]];
        [controller release];
		
		
		[HOGlobalData sharedInstance].levelType = HO_AERA_LEVEL3;
		[HOGlobalData sharedInstance].selType = HO_AREA_SEL_FULL;
		
    }
    return self;
}

- (int)getUserId
{
    HOUserInfoController *userController = (HOUserInfoController *)[self getController:HO_MODULE_TYPE_USER];
    HOUserInfoDataModule *userDataModule = (HOUserInfoDataModule *)[userController getDataModule];
    int userId = [userDataModule getUserId];
    return userId;
}

- (void)saveToken:(NSString *)token
{
	HOUserInfoController *userController = (HOUserInfoController *)[self getController:HO_MODULE_TYPE_USER];
	HOUserInfoDataModule *userDataModule = (HOUserInfoDataModule *)[userController getDataModule];
	[userDataModule saveToken:token];
}

- (void)test
{
    HOAppController *controller = (HOAppController *)[self getController:HO_MODULE_TYPE_APP];
    HOAppDataModule *dataModule = (HOAppDataModule *)[controller getDataModule];
    [dataModule getIsNeedGestureLockWithUserId:[self getUserId]];
}

- (void)checkToken
{
	[HOGlobalData sharedInstance].isLoggedin = [self isLoggedinBefore];
	if([HOGlobalData sharedInstance].isLoggedin)
	{
		[self didLogin];
	}
}

- (void)checkNotification
{
#if 0
		HOAppController *controller = (HOAppController *)[self getController:HO_MODULE_TYPE_APP];
		HOAppDataModule *dataModule = (HOAppDataModule *)[controller getDataModule];
	[[HOJPushHandler sharedInstance] openPushNotification:YES];
	if([dataModule isFirstEnterApp])
	{
		return;
	}
	
	BOOL isRegusterNotfication = NO;
	if(IS_LESSTHAN_IOS8)
	{
		UIRemoteNotificationType types = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
		isRegusterNotfication = types & UIRemoteNotificationTypeAlert;
	}
	else
	{
		isRegusterNotfication = [UIApplication sharedApplication].isRegisteredForRemoteNotifications;
	}
	
	
	
	if (isRegusterNotfication) {
		[HOJPushHandler sharedInstance].isNotificationOpened = YES;
		NSData *deviceToken = [self getDeviceToken];
		if(deviceToken != nil && ![HOGlobalData sharedInstance].isSentDeviceToken)
		{
			[HOGlobalData sharedInstance].isSentDeviceToken = YES;
			[JPUSHService registerDeviceToken:deviceToken];
		}
		LogInf(@"app recieved notification from remote");
		
	}else{
		LogInf(@"app did not recieve notification");
		[HOJPushHandler sharedInstance].isNotificationOpened = NO;
		
	}
	if(![HOJPushHandler sharedInstance].isNotificationOpened)
	{
		if([HOGlobalData sharedInstance].isPopedUpAlertForNotifaction)
			return;
		//        [HOGlobalData sharedInstance].isPopedUpAlertForNotifaction = YES;
		[self sendCommand:kHO_CMD_CANNT_RECEIVE_NOTIFACTION
				 data:nil
			toModules:@[[NSNumber numberWithInt:HO_MODULE_TYPE_APP],
						[NSNumber numberWithInt:HO_MODULE_TYPE_USER],
						[NSNumber numberWithInt:HO_MODULE_TYPE_MESSAGE],
						[NSNumber numberWithInt:HO_MODULE_TYPE_MY]]];
	}
#endif
}

- (NSData *)getDeviceToken
{
	NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
	return [userDefaults objectForKey:@"deviceToken"];
}


- (void)didGetJPushRegistrationID:(NSString *)jid
{
	if(jid == nil)
		return;
	if (jid.length > 0)
	{
		if([HOGlobalData sharedInstance].isLoggedin)
		{
			LogNor(@"kHO_ACTION_UploadJpush didGetJPushRegistrationID");
			[[self getController:HO_MODULE_TYPE_APP] sendRequestWithParams:@{kHO_FIELD_Action:kHO_ACTION_UploadJpush,
																			 kHO_FIELD_JPushRegisterID:[HOJPushHandler sharedInstance].jPushRegistrationID}];
		}
		else
		{
			
			
			LogNor(@"didGetJPushRegistrationID self.isLoggedin == NO");
		}
		[self sendCommand:kHO_CMD_Got_JPush_RegistrationID
					 data:(HOBaseObject *)[HOJPushHandler sharedInstance].jPushRegistrationID];
	}
}

- (void)networkDidReceiveMessage:(NSNotification *)notification
{
	LogNor(@"JSPush networkDidReceiveMessage");
	NSDictionary *userInfo = [notification userInfo];
	[[NSNotificationCenter defaultCenter] postNotificationName:kHO_CMD_UrgencyMessage
														object:nil
													  userInfo:userInfo];
	[self sendCommand:kHO_CMD_ReceiveNotificationMessage data:userInfo];
	return;
}
#pragma mark
- (UIViewController *)getFirstViewController
{
//	return [[[HOWelcomeController alloc]init] autorelease];
//	return [[[HOLoginViewController alloc] initWithModule:HO_MODULE_TYPE_USER] autorelease];
    BOOL isFirstLaunch = NO;
    if (![[NSUserDefaults standardUserDefaults] boolForKey:@"everLaunched"]) {
        isFirstLaunch = YES;
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"everLaunched"];
    }
    if(isFirstLaunch)
    {
       return [[[HOWelcomeController alloc]init] autorelease];
    }
	
//    HOAppController *controller = (HOAppController *)[self getController:HO_MODULE_TYPE_APP];
//    HOAppDataModule *dataModule = (HOAppDataModule *)[controller getDataModule];
    if([HOGlobalData sharedInstance].isLoggedin)
    {
		return [[[HOTabViewController alloc] init] autorelease];
    }
    else
    {
        
//        [self clearCache];
//        int userId = [[HOUIMgr sharedInstance] getUserId];
//        [dataModule clearLockedPasswordWithUserId:userId];
        return [[[HOLoginViewController alloc] initWithModule:HO_MODULE_TYPE_USER] autorelease];
//        return [[[HOTabViewController alloc] init] autorelease];
    }
    
    return [[[HOLoginViewController alloc] initWithModule:HO_MODULE_TYPE_USER] autorelease];

}

- (void)removeObserverFromListener:(UIViewController *)viewController
{
    
    [[self getController:HO_MODULE_TYPE_USER] removeListener:(HOBaseViewController *)viewController];
    [[self getController:HO_MODULE_TYPE_MESSAGE] removeListener:(HOBaseViewController *)viewController];
    [[self getController:HO_MODULE_TYPE_APP] removeListener:(HOBaseViewController *)viewController];
    [[self getController:HO_MODULE_TYPE_MY] removeListener:(HOBaseViewController *)viewController];

}
#pragma mark - -- check local token --

- (BOOL)isLoggedinBefore
{
	NSString *token = [self getToken];
	return (token != nil && token.length > 0);
}

- (NSString *)getToken
{
	HOUserInfoController *controller = (HOUserInfoController *)[self getController:HO_MODULE_TYPE_USER];
	NSString *token = [controller getToken];
	return token;
}

#pragma mark - -- for request --

- (HOBaseController * )getController:(HO_MODULE_TYPE)moduleType
{
    return [controlerListenerDic objectForKey:[NSNumber numberWithInt:moduleType]];
}

- (void)sendRequest:(HOBaseRequestEntity *)request
{
    if((![request.action isEqualToString:kHO_ACTION_Login])
        && (![request.action isEqualToString:kHO_ACTION_MobileReg])
       && (![request.action isEqualToString:kHO_ACTION_AppVersion]))
    {
        NSString *token = [((HOUserInfoController *)[self getController:HO_MODULE_TYPE_USER]) getToken];
        if(token != nil)
		{
            [request addParam:token forKey:kHO_FIELD_Token];
			
		}
		else
		{
			LogNor(@"error! action:%@", request.action);
		}
    }
	LogInf(@"+++++++++++AMBaseController - sendRequest params ++++++++++++++++++nn:%@ \n ++++++++++++++", request.params);

    [httpMgr sendRequest:request];
}


- (void)cancel:(HOBaseRequestEntity *)request
{
    [httpMgr cancel:request];
}

#pragma mark - -- for UI listener --

- (void)sendCommand:(NSString *)action data:(id)data toModules:(NSArray *)moduleLiseners
{
    for(int i = 0; i < [moduleLiseners count]; i++)
    {
        NSNumber *moduleType =[moduleLiseners objectAtIndex:i];
        NSObject<HOControllerDelegate> *controller = [controlerListenerDic objectForKey:moduleType];
        [controller didReceiveCommand:action data:data];
    }
}

- (void)sendCommand:(NSString *)action data:(id)data
{
	NSArray *moduleListerners = [controlerListenerDic allKeys];
	for(int i = 0; i < [moduleListerners count]; i++)
	{
		NSNumber *moduleType =[moduleListerners objectAtIndex:i];
		NSObject<HOControllerDelegate> *controller = [controlerListenerDic objectForKey:moduleType];
		[controller didReceiveCommand:action data:data];
	}
}

- (void)didReceiveResponse:(HOBaseResponseEntity *)response
{
	NSArray *moduleListerners = [controlerListenerDic allKeys];
    for(int i = 0; i < [moduleListerners count]; i++)
    {
        NSNumber *moduleType =[moduleListerners objectAtIndex:i];
        NSObject<HOControllerDelegate> *controller = [controlerListenerDic objectForKey:moduleType];
        [controller didReceiveResponse:response];
    }
}

#pragma mark - -- for handle app level --
- (void)didLogin
{
	[HOGlobalData sharedInstance].isLoggedin = YES;
    NSArray *keys = [controlerListenerDic allKeys];
    for(int i = 0; i < [keys count]; i++)
    {
        NSNumber *moduleType =[keys objectAtIndex:i];
        NSObject<HOControllerDelegate> *controller = [controlerListenerDic objectForKey:moduleType];
        [controller didLogin];
    }
}
- (BOOL)hasUnreadMsg
{
    return [((HOMessageController *)[self getController:HO_MODULE_TYPE_MESSAGE]) hasUnreadMsg];
}
- (void)getNewMessage
{
//    return;
	[((HOMessageController *)[self getController:HO_MODULE_TYPE_MESSAGE]) getNewMessage];
}
- (void)logout
{
    LogInf(@"HOUIMgr didLogout");
	[self cleanup];

}

- (void)requestUserInfoWithUserId:(int)userId
{
//	[[self getController:HO_MODULE_TYPE_APP] sendRequestWithParams:@{kHO_FIELD_Action:kHO_ACTION_GetUserDetail,
//										kHO_FIELD_Id:[NSNumber numberWithInt:userId]}];
}
#pragma mark 

- (void)checkVersion
{
//	return;
    if([HOGlobalData sharedInstance].isNeedCheckVersion)
    {
//        isNeedCheckVersion = NO;
//        HOAppController *controller = (HOAppController *)[self getController:HO_MODULE_TYPE_APP];
//        [controller checkVersion];
		dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
			BOOL needsUpdate = [self needsUpdate];
			dispatch_async(dispatch_get_main_queue(), ^{
				// 更新界面
				if(needsUpdate)
				{
					if([[HOUIMgr sharedInstance].currentScreen isKindOfClass:[HOBaseViewController class]])
					{
						[((HOBaseViewController *)[HOUIMgr sharedInstance].currentScreen) popupUpdateVersion];
					}
				}
			});
		});
    }
}

- (BOOL) needsUpdate
{
	//1099599739
	NSDictionary* infoDictionary = [[NSBundle mainBundle] infoDictionary];
	NSString* appID = infoDictionary[@"CFBundleIdentifier"];//@"1220454821";
	NSURL* url = [NSURL URLWithString:[NSString stringWithFormat:@"http://itunes.apple.com/cn/lookup?bundleId=%@", appID]];
	NSData* data = [NSData dataWithContentsOfURL:url];
	if(data == nil)
		return NO;
	NSDictionary* lookup = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
	
	if ([lookup[@"resultCount"] integerValue] == 1){
		NSString* releasedVersion = lookup[@"results"][0][@"version"];
		NSString* currentVersion = infoDictionary[@"CFBundleShortVersionString"];
		LogWar(@"releasedVersion:%@", releasedVersion);
		LogWar(@"currentVersion:%@", currentVersion);
		int releasedVersionValue = [self getIntFromVersion:releasedVersion];
		int currentVersionValue = [self getIntFromVersion:currentVersion];
		LogWar(@"releasedVersionValue:%d", releasedVersionValue);
		LogWar(@"currentVersionValue:%d", currentVersionValue);
		if(releasedVersionValue > currentVersionValue)
		{
			NSLog(@"Need to update [%@ > %@]", releasedVersion, currentVersion);
			
			return YES;
		}
		
	}
	return NO;
}
- (int)getIntFromVersion:(NSString *)version
{
	NSArray *array = [version componentsSeparatedByString:@"."];
	int versionValue = 0;
	for(int i = 0; i < [array count]; i++)
	{
		if(i == 0)
		{
			versionValue = versionValue + [[array objectAtIndex:0] intValue] * 1000;
		}
		else if(i == 1)
		{
			versionValue = versionValue + [[array objectAtIndex:1] intValue] * 100;
		}
		else if(i == 2)
		{
			versionValue = versionValue + [[array objectAtIndex:2] intValue];
		}
	}
	return versionValue;
	
}


//- (void)didReadNewMessageFromDB
//{
//    [self didReceiveCommand:kHO_CMD_READ_MESSAGE_FROMDB data:nil toModules:@[[NSNumber numberWithInt:HO_MODULE_TYPE_APP]]];
//}


// log NSSet with UTF8
// if not ,log will be \Uxxx
- (NSString *)logDic:(NSDictionary *)dic {
    if (![dic count]) {
        return nil;
    }
    NSString *tempStr1 =
    [[dic description] stringByReplacingOccurrencesOfString:@"\\u"
                                                 withString:@"\\U"];
    NSString *tempStr2 =
    [tempStr1 stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
    NSString *tempStr3 =
    [[@"\"" stringByAppendingString:tempStr2] stringByAppendingString:@"\""];
    NSData *tempData = [tempStr3 dataUsingEncoding:NSUTF8StringEncoding];
    NSString *str = nil;
    if(IS_MORETHAN_IOS8)
    {
        str = [NSPropertyListSerialization propertyListWithData:tempData
                                                        options:NSPropertyListImmutable
                                                         format:NULL
                                                          error:NULL];
    }
    else
    {
        str = [NSPropertyListSerialization propertyListFromData:tempData
                                         mutabilityOption:NSPropertyListImmutable
                                                   format:NULL
                                         errorDescription:NULL];
    }
    return str;
}

- (void)didReceiveRemoteNotification:(NSDictionary *)userInfo
{

	LogImp(@"didReceiveRemoteNotification:%@", userInfo);
    _notificationCount++;
    [self getNewMessage];
    [HOGlobalData sharedInstance].needHandlePushMessage = YES;
	[[NSNotificationCenter defaultCenter] postNotificationName:kHO_CMD_UrgencyMessage
														object:nil
													  userInfo:userInfo];
	[self sendCommand:kHO_CMD_ReceiveNotificationMessage data:userInfo];
}

- (void)addMessageCount
{
    _messageCount++;
}

- (void)cleanup
{
	[HOGlobalData sharedInstance].isLoggedin = NO;
	[[HOStaticDataMgr sharedInstance] cleanup];
	[[HOGlobalData sharedInstance] cleanup];
	[[HOJPushHandler sharedInstance] cleanup];
	
	_notificationCount = 0;
	_messageCount = 0;
	[userInfoDic removeAllObjects];
	NSArray *keys = [controlerListenerDic allKeys];
	for(int i = 0; i < [keys count]; i++)
	{
		NSNumber *moduleType =[keys objectAtIndex:i];
		NSObject<HOControllerDelegate> *controller = [controlerListenerDic objectForKey:moduleType];
		if([controller isKindOfClass:[HOUserInfoController class]])
		{
			//			NSLog(@"tag");
		}
		[controller logout];
	}
	
	[self sendCommand:kHO_CMD_Logout data:nil];
}

#pragma mark
- (void)dealloc
{
    [controlerListenerDic release];
    [super dealloc];
}

@end
